package top.italks.esp32app.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import top.italks.esp32app.R;

public class BluetoothListAdapter extends RecyclerView.Adapter<BluetoothListAdapter.BluetoothViewHolder> {
    private List<BluetoothDevice> deviceList;
    private OnClickListener onClickListener;

    public OnClickListener getOnClickListener() {
        return onClickListener;
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public List<BluetoothDevice> getDeviceList() {
        return deviceList;
    }

    public void setDeviceList(List<BluetoothDevice> deviceList) {
        this.deviceList = deviceList;
    }
    public interface OnClickListener{
        void OnItemClick(int position,BluetoothDevice device);
    }

    @NonNull
    @Override
    public BluetoothViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.bluetooth_list_item, parent, false);
        return new BluetoothViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BluetoothViewHolder holder, int position) {
        holder.name.setText(deviceList.get(position).getName()==null?"":deviceList.get(position).getName());
        holder.mac.setText(deviceList.get(position).getAddress());
        holder.itemLayout.setTag(position);
        holder.itemLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onClickListener!=null){
                    onClickListener.OnItemClick((int)v.getTag(),deviceList.get((int)v.getTag()));
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return deviceList.size();
    }

    public class BluetoothViewHolder extends RecyclerView.ViewHolder{
        LinearLayout itemLayout;
        TextView name;
        TextView mac;
        public BluetoothViewHolder(@NonNull View itemView) {
            super(itemView);
            itemLayout=itemView.findViewById(R.id.itemLayout);
            name=itemView.findViewById(R.id.name);
            mac=itemView.findViewById(R.id.mac);
        }
    }
}
